package com.huatai.range.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.range.entity.TabAndAliasEntity;
import com.huatai.range.entity.TrialTableEntity;
import com.huatai.range.mapper.TrialTableMapper;
import com.huatai.range.query.AliasExistQuery;
import com.huatai.range.query.TrialRangeQuery;
import com.huatai.range.service.TrialTableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.range.vo.IsExistVo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 试验信息表; 服务实现类
 * </p>
 *
 * @author luoxc
 * @since 2023-04-18
 */
@Service
public class TrialTableServiceImpl extends ServiceImpl<TrialTableMapper, TrialTableEntity> implements TrialTableService {


	@Override
	public List<TrialTableEntity> listByTrialId(String trialId) {
		if (StringUtil.isEmpty(trialId)) return null;
		return this.list(Wrappers.<TrialTableEntity>lambdaQuery().eq(TrialTableEntity::getTrialId, trialId));
	}

	@Override
	public Object getByTrialId(String trialId) {
		List<TrialTableEntity> tabs =
			this.list(Wrappers.<TrialTableEntity>lambdaQuery().eq(TrialTableEntity::getTrialId, trialId));
		List<Object> list = new ArrayList<>();
		if (tabs.isEmpty()) return null;
		tabs.forEach(tab -> {
			Map<String, Object> map = new HashMap<>();
			map.put("tabName",tab.getTabName());
			map.put("alias",tab.getAlias());
			map.put("tabType",tab.getTabType());
			list.add(map);
		});
		return list;
	}

	@Override
	public List<Map<String, Object>> getTrialList() {
		List<TrialTableEntity> trialTables = this
			.list(Wrappers.<TrialTableEntity>query().select("DISTINCT trial_id,trial_name"));
		if (trialTables.isEmpty()) return null;
		List<Map<String, Object>> tables = new ArrayList<>();
		trialTables.forEach(table -> {
			Map<String, Object> map = new HashMap<>();
			map.put("trialId", table.getTrialId());
			map.put("trialName", table.getTrialName());
			tables.add(map);
		});
		return tables;
	}

	@Override
	public IsExistVo existByAlias(AliasExistQuery aliasExistQuery) {
		TrialTableEntity tableEntity = this.getOne(Wrappers.<TrialTableEntity>lambdaQuery()
			.eq(TrialTableEntity::getTrialId, aliasExistQuery.getTrialId())
			.eq(TrialTableEntity::getAlias, aliasExistQuery.getAlias()));
		return new IsExistVo(!ObjectUtil.isEmpty(tableEntity));
	}

	@Override
	public List<TrialTableEntity> listByTrialIdAndTabType(TrialRangeQuery trialRangeQuery) {
		if (ObjectUtil.isEmpty(trialRangeQuery)) return null;
		return this.list(Wrappers.<TrialTableEntity>lambdaQuery()
			.eq(TrialTableEntity::getTrialId, trialRangeQuery.getTrialId())
			.eq(TrialTableEntity::getTabType, trialRangeQuery.getTabType()));
	}
}
